from functools import wraps

from django.http import JsonResponse

from menu.models import SysRoleMenu
from role.models import SysUserRole


def check_permission(perms_list):
    """
    权限校验装饰器
    :param perms_list: 权限列表
    """

    def decorator(view_func):
        @wraps(view_func)
        def wrapped_view(self, request, *args, **kwargs):  # 直接接收self, request等参数
            # 权限校验逻辑
            username = request.session.get('username')
            role_list = SysUserRole.objects.distinct().filter(user__username=username).values_list('role_id')
            menu_list = SysRoleMenu.objects.filter(role_id__in=role_list).values_list("menu__perms")
            for item in menu_list:
                if item[0] in perms_list:
                    return view_func(self, request, *args, **kwargs)
            return JsonResponse({"code": 4001, "msg": "接口权限校验失败"})

        return wrapped_view

    return decorator
